﻿# -*- coding:utf-8 -*-
#
# Система учета компьютерной техники  
# Структура предприятия
#
import re
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.template import RequestContext, Context

from models import Department, Employee, Phone
from forms import DepartmentForm



letters = ['А','Б','В','Г','Д','Е','Ж','З','И','К','Л','М','Н','О','П','Р','С','Т','У','ф','Х','Ц','Ч','Ш','Щ','Э','Ю','Я','',]




def recursive_get_department_list(department, level):
    res = []
    for di in department:
        item = {"id":di.id,"name":di.name,"parent":di.parent,"level":level,"csslevel":level*24,"phones":di.phone.all()}
        department_set = di.department_set.all()
        item["child_present"] = department_set
        res.append(item)
        subdepartments=recursive_get_department_list(department_set, level+1)
        res.extend(subdepartments)
    return res



def create_department_tree():
    d = Department.objects.select_related().filter(parent=None)
    return recursive_get_department_list(d, 0)



def create_department_tree_ex(parent=None):
    d = Department.objects.select_related().filter(parent=parent)
    return recursive_get_department_list(d, 0)



def render_to(request, template, context):
    root_department = Department.objects.filter(parent=None)
    context_extra = Context({
        'root_department':root_department,
        'letters':letters,
    })
    return render_to_response(template, context, context_instance=RequestContext(request, context_extra))







#
# Адресная книга
#
def index(request): 
    context = Context({
    })
    return render_to(request, 'shm/addressbook_index.html', context)



def dep_list(request, department_id): 
    department = Department.objects.get(id=department_id)
    department_tree = create_department_tree_ex(parent=department)
    context = Context({
      'department': department,
      'department_tree':department_tree,
    })
    return render_to(request, 'shm/addressbook_department_list.html', context)
    
    
def employee_list(request, root_department_id, department_id): 
    department =   Department.objects.get(id=root_department_id)  
    department_tree = create_department_tree_ex(parent=department)
    department_detail = Department.objects.get(id=department_id)  
    employee = Employee.objects.filter(department=department_detail, boss=False)
    employees = [{'employee':e, 'phones':e.phone.all()} for e in employee]
    phone = department_detail.phone.all()
    boss = Employee.objects.filter(department=department_detail, boss=True)
    bosses = [{'boss':e, 'phones':e.phone.all()} for e in boss]
    context = Context({
      'department_detail': department_detail,
      'employee':employees,
      'phone':phone,
      'boss':bosses,
      'department':department,
      'department_tree':department_tree,
    })
    return render_to(request, 'shm/addressbook_employee_list.html', context)



def addressbook_employee_letter(request, letter_id):
    employee = Employee.objects.filter(last_name__istartswith=letters[int(letter_id)])
    employees = [{'employee':e, 'phones':e.phone.all()} for e in employee]
    
    half = (len(employees)/2)
    employees_0 = employees[:half]
    employees_1 = employees[half:]
    
    context = Context({
      #'employee': employees,
        'employees_0': employees_0,
        'employees_1': employees_1,
    })
    return render_to(request, 'shm/addressbook_employee_letter.html', context)   
    
    
    
    
    
#
# структура предприятия
#
def department_employee_update(request, department_id):
    department_detail = Department.objects.get(id=department_id)  
    employee = Employee.objects.filter(department=department_detail)#, fired=False
    phone = department_detail.phone.all()
    message_ok = ''
    if request.method == 'POST':
        checkbox_id = [x.replace('empl_id_', '') for x in request.POST if x.startswith('empl_id_')]        
        hidden_id = [x.replace('empl_hid_', '') for x in request.POST if x.startswith('empl_hid_')] 
    
        checkbox = {}
        
        for item in hidden_id:
            checkbox[int(item)] = {"boss":False,"responsible":False, "it_staff":False, "fired":False}    
        
        for item in checkbox_id:
            res = re.search(r'(.*)_(\d+)',item)
            if res:
                id = int(res.group(2))
                cb_name = res.group(1)
                checkbox[id][cb_name] = True

        for  key, value in checkbox.items():
            empl = get_object_or_404(Employee, id=key)
            empl.boss = value["boss"]
            empl.responsible = value["responsible"]
            empl.it_staff = value["it_staff"]
            empl.fired = value["fired"]
            empl.save()

    form = DepartmentForm(instance=department_detail)
    context = Context({
      'department_detail': department_detail,
      'employee':employee,
      'phone':phone,
      'form':form,
      'message_ok':message_ok,
    })
    return render_to(request, 'shm/department_item.html', context)



    
def department_detail(request, department_id): 
    #department =   Department.objects.get(id=root_department_id)  
    #boss = Employee.objects.get(department=department_detail, boss=True)    
    #department_tree = create_department_tree_ex(parent=department)
    
    department_detail = Department.objects.get(id=department_id)  
    employee = Employee.objects.filter(department=department_detail, fired=False)
    phone = department_detail.phone.all()
    message_ok = ''
    if request.method == 'POST':
        form = DepartmentForm(request.POST, request.FILES, instance=department_detail)
        if form.is_valid():
            form.save()
            message_ok = 'Saved seccefuly.'
    else:
        form = DepartmentForm(instance=department_detail)
    context = Context({
      'department_detail': department_detail,
      'employee':employee,
      'phone':phone,
      'form':form,
      'message_ok':message_ok,
    })
    return render_to(request, 'shm/department_item.html', context)





def department_tree(request):
    department_tree = Department.objects.select_related().all()
    context = Context({
      'department_tree':department_tree,
      
    })
    #return render_to(request, 'shm/department_tree.html', context) 
    return render_to(request, 'shm/department_tree_tag.html', context) 


def department_tree_ch(request, department_id): 
    department_tree = Department.objects.filter(parent=department_id)
    context = Context({
      'department_tree':department_tree,
    })
    return render_to(request, 'shm/tree_item.html', context) 
    
    
    
    
    
    